package com.jason.Gmail.Connection;

import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

import com.jason.Errors.ShowErrors;

public class InboxReader {

	/**
	 * @return the success
	 */
	public Boolean getSuccess() {
		return success;
	}

	private String userName;
	private String password;
	private String searchTerm;
	private Boolean success = false;
	ArrayList<String> aList = new ArrayList<String>();
	

	/**
	 * @param userName the userName to set
	 */
	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the searchTerm
	 */
	public String getSearchTerm() {
		return searchTerm;
	}

	/**
	 * @param searchTerm the searchTerm to set
	 */
	public void setSearchTerm(String searchTerm) {
		this.searchTerm = searchTerm;
	}

	public void connect() {
		 
		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "imaps");
		try {
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("imaps");
			store.connect("imap.gmail.com", userName, password);
			System.out.println(store);

			Folder inbox = store.getFolder("Inbox");
			inbox.open(Folder.READ_ONLY);
			FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
			Message messages[] = inbox.search(ft);
			int x = 0;
			for(Message message:messages) {
				Address[] a_message = message.getFrom();
				aList.add(a_message[0].toString());
				System.out.println(aList.get(x).toString());
				x++;
			}
			
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			error.display(e);
		} catch (MessagingException e) {
			e.printStackTrace();
			error.display(e);
		}
	}
	
	private ShowErrors error = new ShowErrors();
	
	public Boolean findEmail(String searchTerm){
		for (int x = 0; aList.size() > x; x++){
			if (aList.get(x).contains(searchTerm)){
				success = true;
			}
		}
		return success;
	}
}
